package com.hbnu.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbnu.system.mapper.DeptMapper;
import com.hbnu.system.mapper.IdToStatsMapper;
import com.hbnu.system.model.dto.IdToStatsDTO;
import com.hbnu.system.model.entity.User;
import com.hbnu.system.service.IDeptService;
import com.hbnu.system.service.IUserService;
import com.hbnu.system.service.IdToStatsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class IdToStatsImpl extends ServiceImpl< IdToStatsMapper, IdToStatsDTO> implements IdToStatsService {


    @Autowired
    IUserService iUserService;

    @Autowired
    IDeptService iDeptService;

    @Autowired
    DeptMapper deptMapper;

    @Override
    public String IdToName(String nameid){
        User user = iUserService.getOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getUid, nameid));
        return user != null ? user.getName() : "未知用户";
    }

    @Override
    public String IdToAllauthor(String allauthorid) {
        if (allauthorid == null || allauthorid.isEmpty()) {
            return "";
        }

        // 解析用户ID列表，过滤掉空值和0
        List<String> userIds = Arrays.stream(allauthorid.split(","))
                .map(String::trim)
                .filter(id -> !id.isEmpty() && !"0".equals(id))
                .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);

        if (userIds.isEmpty()) {
            return "";
        }

        // 一次性查询所有用户信息
        List<User> users = iUserService.list(Wrappers.lambdaQuery(User.class)
                .in(User::getUid, userIds));

        // 创建用户ID到姓名的映射
        Map<String, String> userMap = new HashMap<>();
        for (User user : users) {
            userMap.put(user.getUid(), user.getName());
        }

        // 按原顺序构建姓名列表
        List<String> authorNames = new ArrayList<>();
        for (String userId : userIds) {
            String name = userMap.get(userId);
            if (name != null) {
                authorNames.add(name);
            }
        }

        return String.join(",", authorNames);
    }



    @Override
    public String IdToDept(String deptid){
        String deptName = deptMapper.getDeptNameByDeptID(deptid);
        return deptName;
    }

    @Override
    public String IdToHeadName(String head) {
        User user = iUserService.getOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getUid, head));
        return user != null ? user.getName() : "未知负责人";
    }

    @Override
    public String IdToEntered(String entered) {
        User user = iUserService.getOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getUid, entered));
        return user != null ? user.getName() : "未知录入人";
    }

}
